<?php
namespace Ayhome\Suite\Server;

use Exception;
use FastD\Http\HttpException;
use FastD\Http\Response;
use FastD\Http\SwooleServerRequest;
use FastD\Http\JsonResponse;
use Psr\Http\Message\ServerRequestInterface;

use think\facade\Cache;
use swoole_server;
use swoole_http_request;
use swoole_http_response;
class Http extends \FastD\Swoole\Server\HTTP
{
  public function doRequest(ServerRequestInterface $serverRequest)
  {
    $serverParams = $serverRequest->serverParams;
    $method = $serverRequest->getMethod();
    $get = $serverRequest->getQueryParams();
    $post = $serverRequest->getParsedBody();

    

    $data = $serverRequest->getBody()->__toString();
    request()->body = $data;

    $data =  json_decode($data,true);
    request()->raw = json_encode($data['data']);

    $url = $serverParams['REQUEST_URI'];
    if (strlen($url) < 2) {
      return new JsonResponse([
        'code'=>200,
        'serverParams'=>$serverParams,
        'msg'=>'url不能为空',
      ]);
    }
    // print_r($url."\n");
    if ($url == "/base/gate/mac") {
      // print_r($data);
      print_r($serverRequest->getBody()->__toString());
    }

    $path_arr = explode("/", $url);
    print_r($path_arr,"\n");
    $action = $path_arr[count($path_arr) - 1];
    $cls = $path_arr[2].'/'.$path_arr[3];

    $post = $data['post'];
    

    try {
      $ret = action($cls, $post, $path_arr[1].'\controller');
      $r = $ret->getContent();
      return new JsonResponse(json_decode($r,true));
    } catch (Exception $e) {
      return new JsonResponse([
        'msg'=>$e->getMessage(),
      ]);
    }
    return new JsonResponse([]);

  }

  public function doTask(swoole_server $server, $data, $taskId, $workerId)
  {
    // echo $data . ' on task' . PHP_EOL;
    return $data;
  }

  public function doConnect(swoole_server $server, $fd, $from_id)
  {
    // echo $data . ' on task' . PHP_EOL;
    return $data;
  }

 
}
